package uit.nfcmenu.manager;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class WaiterImageStoreManager {

	public static String StoreByteImage(Context mContext, Bitmap src, 
			int quality, String nameFile, String pathToFolder) {

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		src.compress(CompressFormat.JPEG, quality, os);

		byte[] imageData = os.toByteArray();
		
		// Ex: "/sdcard/myImages"
		String pathToStore = Environment.getExternalStorageDirectory().toString() + pathToFolder;
		
		// Check folder is existed or not
		File folder = new File(pathToStore); 
		boolean success = false;
		if(!folder.exists()) {
		    success = folder.mkdir();
		}         
		if (!success) { 
		    // Do something on success
			pathToStore = folder.toString() + "/" + nameFile + ".jpg";
			FileOutputStream fileOutputStream = null;
			try {
				
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 5;
				
				Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
						imageData.length, options);
				
				fileOutputStream = new FileOutputStream(pathToStore);
				
				BufferedOutputStream bos = new BufferedOutputStream(
						fileOutputStream);
				
				myImage.compress(CompressFormat.JPEG, quality, bos);
				
				bos.flush();
				bos.close();
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				// create folder
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else  {
		    // Do something else on failure 
		}

		return pathToStore;
	}
	
//	public static void updateImage(Context mContext, ImageView img, final ItemModel item){
////		final String path = FileCache.getItemSDCardUri(item.getImageLink());
//		int cornerRadius = (int) mContext.getResources().getDimension(R.dimen.corner_radius);
//		int margin = (int) (mContext.getResources().getDimension(R.dimen.detail_margin_left_right)) ;
//		
//		int width = (int) 300 - 2 * margin;
//		int height = (int)300;
//		//Log.w(tag, "width="+width+",height="+height);
//		if (width != 0 && height != 0) {
//			if (!ImageHelper.getImageViewWithRoundCorners(img, item.getBitmap(), 
//					width, height, cornerRadius)) {
//				
//				(new ImageDownloader()).downloadWithBorder(item.getImageLink(), img);
//				// download file, then save to SDCard
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						try {
//							new Download(new URL(item.getImageLink()), path);
//						} catch (MalformedURLException e) {
//							e.printStackTrace();
//						}	
//					}
//				}).start();
//			}
//		} else {
//			// do nothing...
//		}
//	}
}
